package com.loan.controller;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;
import com.loan.common.CONST;
import com.loan.enums.SmsNotify;
import com.loan.model.User;
import com.loan.service.LoggerService;
import com.loan.service.UserService;
import com.loan.util.AES;
import com.loan.util.CheckUtils;
import com.loan.util.DateUtil;
import com.loan.util.Json;
import com.loan.util.MyCaptchaRender;
import com.loan.util.RandomCodeUtil;
import com.loan.util.Sms;
import com.loan.util.Str;

public class SmsController extends Controller {
	private static UserService user = new UserService();
	private static LoggerService log = new LoggerService();
	private static final Logger logger = Logger.getLogger(UserController.class);


	/**
	 * 获取图形验证码
	 */
	@Clear  
	public void verifyCode() throws Exception {
		getResponse().setHeader("Access-Control-Allow-Origin","*"); 
		int cid = getParaToInt("cid",2);
		String mobile = getParaToInt("aes",1)==1 ? AES.decode(getPara("mobile","")) : getPara("mobile",""); 			
		if(CheckUtils.checkMoible(mobile)) { 
			render(new MyCaptchaRender(cid+mobile,60,22,4,true));
		}else {
			renderJson(Json.error("手机号码不正确！"));
		}
	}
	
	/**
	 * 获取短信验证码
	 */
	@Clear
	public void index() { 
		getResponse().setHeader("Access-Control-Allow-Origin","*"); 
		int aes = getParaToInt("aes",1);
		int cid = getParaToInt("cid",2);
		String mobile = aes==1 ? AES.decode(getPara("mobile","")) : getPara("mobile",""); 			
		String verifyCode = getPara("verifyCode","");
		if(Str.isBlank(verifyCode) || !verifyCode.equalsIgnoreCase(CONST.getAttr("verifyCode"+cid+mobile))) {
    		renderJson(Json.error("图形验证码不正确！"));
    		return ;
		}
		if(CheckUtils.checkMoible(mobile)) { 
			String type = getPara("type","reg"); 
			String dateStr = CONST.getAttr("sendCode"+mobile);
			if(Str.eq("modifyMobileNew", type) || !Str.nb(dateStr) || Long.valueOf(DateUtil.getTimeStamp())-Long.valueOf(dateStr)>=0){
				String business = ""; 
				String contents = ""; 
				String code = RandomCodeUtil.getCode();
				if(Str.eq("reg", type)){	// 注册短信验证码
					// 检查用户已经注册
					if(user.findByMobile(cid,mobile)!=null){
			    		renderJson(Json.error("该手机号已注册！"));
			    		return ;
					} 
					business = "注册";
					contents = Str.format(SmsNotify.REG, code, CONST.find("PLAT_PHONE"));
				}else if(Str.eq("resetPassword", type)){		// 重置/修改登陆密码短信验证码
					// 检查用户是否已注册
					if(user.findByMobile(cid,mobile)==null){
			    		renderJson(Json.error("对不起该手机还未注册哦！"));
			    		return ; 
					}
					business = "修改登陆密码";
					contents = Str.format(SmsNotify.RESSET_PASSWORD, code, CONST.find("PLAT_PHONE"));
				}else if(Str.eq("modifyMobileOld", type)){		// 修改登陆手机号（旧）
					business = "修改原有登陆手机号";
					contents = Str.format(SmsNotify.MODIFY_MOBILE, code, CONST.find("PLAT_PHONE"));
				}else if(Str.eq("modifyMobileNew", type)){		// 修改登陆手机号（新）
					// 检查用户已经注册 
					if(user.findByMobile(cid,mobile)!=null){
			    		renderJson(Json.error("该手机号已注册！"));
			    		return ; 
					}
					business = "修改新登陆手机号";
					contents = Str.format(SmsNotify.MODIFY_MOBILE, code, CONST.find("PLAT_PHONE"));
				} 
				String res = "1";//Sms.send(mobile, contents);
				CONST.setAttr(type+mobile, code);
				CONST.setAttr("sendCode"+mobile, String.valueOf(new Date().getTime()+60000));
				User u = user.findByMobile(cid,mobile); 
				log.build(business+"发送短信", "手机号码："+mobile+" 验证码："+code, u!=null?u.getId():0, "user");
		        if(Str.nb(res)){
		        	logger.error("手机号："+mobile+" 内容："+contents+" 发送反馈："+res);
		    		renderJson(Json.ok("短信发送成功！",code));
		        } else {
		    		renderJson(Json.error("短信发送失败！"));
		        }
			} else {
				renderJson(Json.error("操作过于频繁，请稍候再试！"));
			} 
		} else {
    		renderJson(Json.error("手机格式不正确！"));
        }
	}
	
	/**
	 *  群发短信
	 * @throws Exception 
	 */ 
	public void mass() throws Exception{
		User u = getAttr("user");
		String type = getPara("type","multiple");
		String contents = getPara("contents");
		String summary = getPara("summary");
		List<User> users = new ArrayList<User>();
		
		if(Str.nb(type) && Str.nb(contents) && Str.nb(summary)) {
			if(Str.eq("all", type)) {
				users = User.dao.find("select * from user");
			}else if(Str.eq("multiple", type)){
				for(String m : summary.split(",")) {
					User u1 = new User();
					u1.setMobile(m);
					users.add(u1);
				}
			}else if(Str.eq("sql", type)){
				users = User.dao.find(summary);
			}
			String us = "";
			for(User t : users) {
				if(t!=null && Str.nb(t.getMobile()) && CheckUtils.checkMoible(u.getMobile())) {
					us += t.getMobile()+",";
				} 
			}
			String res = Sms.send(us, contents, "1012812");
			System.out.println(res);
			
			renderJson(Json.ok("短信群发成功！"));
		} else {
    		renderJson(Json.error("发送参数不正确！"));
        }
	}	
	
	public static void main(String[] args) {
		try {
	    	Document document = 
	    		DocumentHelper.parseText("<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n" + 
	    			"<CSubmitState xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://tempuri.org/\">\r\n" + 
	    			"  <State>0</State>\r\n" + 
	    			"  <MsgID>1711240856246673963</MsgID>\r\n" + 
	    			"  <MsgState>提交成功</MsgState>\r\n" + 
	    			"  <Reserve>2</Reserve>\r\n" + 
	    			"</CSubmitState>");
	    	Element root = document.getRootElement();  
	    	@SuppressWarnings("unchecked")
			List<Attribute> list = root.attributes();  
	        //遍历属性节点  
	        for(Attribute attribute : list){  
	            System.out.println("属性"+attribute.getName() +":" + attribute.getValue());  
	        }  
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			
		}
    }
}
 